package com.ysw.sql;

import com.ysw.annotation.*;
import com.ysw.config.Function;
import com.ysw.config.MapperBean;

import javax.crypto.interfaces.PBEKey;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author legion
 */
public class MyMapperProxy implements InvocationHandler {
    private Mysql mysql;
    private MyConfig myConfig;


    public MyMapperProxy(Mysql mysql, MyConfig myConfig) {
        this.mysql = mysql;
        this.myConfig = myConfig;
    }


        /**
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     */

    @Override
    public Object invoke(Object proxy, Method method,Object[] args) throws SQLException {
        MapperBean mapperBean=myConfig.readMapper("StuMapper.xml");
        //判读xml是不是对应接口
        if(!method.getDeclaringClass().getName().equals(mapperBean.getInterfaceName())){
            System.out.println(".......xml不是其对应接口........");
        }
        List<Function> list=mapperBean.getList();
        if(list!=null||list.size()!=0){
            for(Function function:list){
                //判断id是否和接口方法一致
                if(judge(method,function,"selectById")){
                    return mysql.selectOne(function.getSql(),String.valueOf(args[0]));
                }
                if(judge(method,function,"deleteById")){
                    mysql.deletetOne(function.getSql(),String.valueOf(args[0]));
                }
                if(judge(method,function,"insert")){
                    mysql.insertOne(function.getSql(),String.valueOf(args[0]));
                }
                if(judge(method,function,"updateById")){
                    mysql.updataOne(function.getSql(),String.valueOf(args[0]));
                }
            }
        }
        return null;
    }
    /**
     * 判断mapper文件中id是否一致
     * @param method
     * @param function
     * @param methodId
     * @return
     */
    private boolean judge(Method method, Function function, String methodId) {
        if(method.getName().equals(function.getFunctionName())&&function.getFunctionName().equals(methodId)){
            return true;
        }else{
            return false;
        }
    }
}
